﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WinFormCenter.page {
    public partial class Form_Draw_Tree : Form {
        private Graphics? graphics;
        const double PI = Math.PI;
        const double th1 = 35 * PI / 180;
        const double th2 = 25 * PI / 180;
        const double per1 = 0.6, per2 = 0.7;
        readonly Random rnd = new();
        public Form_Draw_Tree() {
            InitializeComponent();
            this.AutoScaleBaseSize = new System.Drawing.Size(6,14);
            this.ClientSize = new System.Drawing.Size(400,400);
            this.Paint += Form1_Paint;
            this.Click += Redraw;
        }

        private void Redraw(object? sender, EventArgs e) {
            this.Invalidate();
        }
       
        double Random() {
            return rnd.NextDouble();
        }
        private void Form1_Paint(object? sender, PaintEventArgs e) {
            graphics = e.Graphics;
            DrawTree(10, 200, 380, 100, -PI / 2);
        }
        void DrawTree(int n,double x0,double y0,double length,double th) {
            if (n == 0) {
                return;
            }
            double x1 = x0 + length * Math.Cos(th);
            double y1=y0+length * Math.Sin(th);
            DrawLine(x0,y0,x1,y1);
            DrawTree(n - 1, x1,y1, per1 * length * (0.5 + Random()), th + th1 * (0.5 + Random()));
            DrawTree(n - 1, x1, y1, per2 * length * (0.4 + Random()), th + th2 * (0.5 + Random()));
            if (Random() > 0.6) {
                DrawTree(n-1,x1,y1,per2*length*(0.4+Random()),th-th2*(0.5+Random()));
            }
        }
        void DrawLine(double x0, double y0, double x1, double y1) {
            graphics?.DrawLine(Pens.Blue, (int)x0, (int)y0, (int)x1, (int)y1);
        }
    }
}
